import { Component, OnInit, Input, OnDestroy, ViewChild } from "@angular/core";

import { ModalController, IonInfiniteScroll } from "@ionic/angular";

import { Subscription } from "rxjs";

import { MessageService } from "src/app/shared/service/message.service";
import { HttpService } from "src/app/shared/service/http.service";

import { until } from "protractor";
import { SharePageComponent } from 'src/app/coms/share-page/share-page.component';
import { AppGlobalService } from "./../../shared/service/app-global.service";

@Component({
  selector: "app-consultant-list",
  templateUrl: "./consultant-list.component.html",
  styleUrls: ["./consultant-list.component.scss"]
})
/**
 * 新案例列表标签
 */
export class ConsultantListComponent implements OnInit, OnDestroy {
  @ViewChild("contentId") content;
  // 组件数据
  @Input() tagData: any = {};
  // 声明订阅对象
  subscription: Subscription = null;

  // 筛选及页面数据参数
  params: any = {};

  // 当前页数，默认1
  pageNo = 1;

  // size
  pageSize: number;

  // 数量
  pageTotal: number;

  listData: any;

  defaultImg = "assets/img/headtrait.png";
  showName = "";
  
  constructor(
    private appGlobalService: AppGlobalService,
    private message: MessageService,
    private http: HttpService,
    private modalController: ModalController
  ) { }

  ngOnInit() {
    const that = this;
    if (this.tagData.data.submit) {
      this.params = this.tagData.data.submit;
      this.params.sessionId = localStorage.getItem("sessionId");
    }

    this.listData = this.tagData.data.data;

    this.pageSize = this.tagData.pageSize;
    this.pageTotal = this.tagData.pageTotal;

    if (!this.subscription) {
      if (this.tagData.data.submit.content && this.tagData.data.submit.content.showName) {
        sessionStorage.setItem("showName", this.tagData.data.submit.content.showName);
      } else {
        sessionStorage.removeItem('showName');
      }
      // 获取筛选参数
      this.subscription = this.message.getMessage().subscribe(param => {
        if (param) {
          this.showName = param.showName;
          // // 重置当前页数
          this.pageNo = 1;
          // 参数
          this.params.content = param || {};
          // 页面数据参数
          this.params.content["pageNo"] = this.pageNo;
          // 请求获取新数据
          this.http.post(
            "application/submit",
            this.params,
            res => {
              // 请求数据成功
              if (res.success && res.data.data && res.data.data.length > 0) {
                this.listData = res.data.data;
                console.log(this.listData, 'this.listData');
              } else {
                this.listData = [];
                // this.appGlobalService.showToast(res.message, 2000, "middle");
              }
              // that.content.scrollToBottom(0);
            },
            err => {
              // 请求数据失败
              this.appGlobalService.showToast(err.message, 2000, "middle");
            }
          );
        }
      });
    }
  }

  ngOnDestroy(): void {
    // 组件生命周期结束的时候，注销
    this.subscription.unsubscribe();
  }

  // 列表跳转
  clickLink(obj) {
    localStorage.setItem("caseDetail", JSON.stringify(obj));
    if (!obj.link) {
      console.log("没有返回link-target");
    }
    const pageParams = {
      pageId: obj.link.target,
      params: obj.link.params,
      sessionId: localStorage.getItem("sessionId")
    };
    this.appGlobalService.goToForward(pageParams);
  }

  // 下拉刷新，保留
  doRefresh(event) { }

  // 上滑加载
  loadMoreData(event) {
    if (this.pageNo >= this.pageTotal) {
      event.target.disabled = true;
      // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
      // event.complete();
      return;
    }
    // // 请求下一个页面
    this.pageNo = this.pageNo + 1;
    // // 参数
    this.params.content["pageNo"] = this.pageNo;
    // 请求获取新数据
    this.http.post(
      "application/submit",
      this.params,
      res => {
        // 请求数据成功
        if (res.success) {
          const resList = res.data.data;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(item => {
              this.listData.push(item);
            });
          } else {
            event.target.disabled = true;
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
          }
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
        event.target.complete();
      },
      err => {
        // 请求失败，更新当前页数
        this.pageNo = this.pageNo - 1;
        // 请求数据失败
        this.appGlobalService.showToast(err.message, 2000, "middle");
        event.target.complete();
      }
    );
  }

  collectionCase(id, index, submitId, pluginId, opportunityId, customerId) {
    try {
      if (document.getElementById('collectionImg' + index)) {
        const img = document.getElementById('collectionImg' + index) as HTMLImageElement;
        const params = {
          content: {
            plugin_id: pluginId,
            opportunity_id: opportunityId,
            customer_id: customerId
          },
          id: submitId,
          sessionId: localStorage.getItem('sessionId')
        };
        this.http.post('application/submit', params, (res) => {
          if (res) {
            if (res.data.status === 0) {
              img.src = "assets/icon/nav_icon_collection_white_nor@3x.png";
            } else {
              img.src = "assets/icon/nav_icon_collection_red_nor@3x.png";
            }
            this.appGlobalService.showToast(res.data.status === 0 ? "取消收藏成功" : "收藏成功", 2000, "bottom");
          }
        });
      }
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  resetCollection(submitId, pluginId, opportunityId, customerId) {
    // let that = this;
    const params = {
      content: {
        plugin_id: pluginId,
        opportunity_id: opportunityId,
        customer_id: customerId
      },
      id: submitId,
      sessionId: localStorage.getItem('sessionId')
    };
    this.http.post('application/submit', params, (res) => {
      if (res) {
        if (res.data.status === 0) {
          this.appGlobalService.showToast("取消收藏成功", 2000, "bottom");
          // this.listData = [];
          setTimeout(() => {
            this.message.sendMessage({
              filter: {
                contract_service_stop_time: null,
                districtWhere_district: null
              },
              order: {},
              showName: this.showName !== "" ? this.showName : "#transfer_myBusiness"
            });
            // this.params.sessionId = localStorage.getItem('sessionId');
            // this.params.content.pageNo = 1;
            // this.http.post('application/submit', this.params, newRes => {
            //   if (newRes.success) {
            //     this.tagData.data.data = newRes.data.data;
            //     this.params.content.pageNo = 2;
            //   } else {
            //     this.pageNo = 1;
            //     this.appGlobalService.showToast(res.message, 2000, 'middle');
            //   }
            // });
          }, 700);
        }

      }
    });
  }



  shareCase(link) {
    if (!link) {
      console.log("没有返回link-target");
    }

    const pageParams = {
      pageId: link.target,
      params: link.params,
      sessionId: localStorage.getItem("sessionId")
    };
    this.http.post('application/page', pageParams, res => {
      console.log(JSON.parse(res.script));
      const tmpShareData = JSON.parse(res.script).views[0].tags[0].data;
      // console.log(tmpShareData);
      this.presentShareModal(tmpShareData);
    });
  }

  // 分享弹框
  async presentShareModal(shareData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: shareData }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }


}
